<template>
  <continer :isNoTabs="true" style="width: calc(100% - 170px)">
    <template slot="search">
      <div
        style="overflow: hidden"
        :style="{
          height: openShow ? 'auto' : '90px',
        }"
      >
        <el-form
          id="searchForm"
          :model="formData"
          label-position="top"
          style="display: flex; flex-wrap: wrap; height: auto"
          @submit.native.prevent
        >
          <el-form-item
            style="margin-right: 20px"
            :label="item.name"
            v-for="(item, index) in chooseFilterField"
            :key="index"
            :prop="item.field"
          >
            <input-type
              :filterModule="true"
              :propData="item"
              :searchShow="true"
              :propValue="formData[item.field]"
              @updatePropValue="updatePropValue"
              @querySearch="handleSearchFunc"
            ></input-type>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template slot="oprate">
      <div v-if="searchHeight > 90" @click="handleLines" class="open">
        <i :class="openShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />{{
          openShow ? "收起" : "展开"
        }}
      </div>
      <customFilter
        name="自定义"
        :newCus="true"
        :filterId="filterId"
        :chooseData="chooseFilterField"
        :getCusAllFields="getCusAllFields"
        @saveFilter="saveFilter"
      />
      <!-- <advancedSearch
        ref="customSearch"
        class="customSearch"
        :fieldList="tableHeaders"
        :fieldSelectList="fieldSelectList"
        :conditionList="conditionList"
        :customList="customList"
        @handleSearch="handleSearch"
      ></advancedSearch> -->
      <el-button type="primary" size="mini" @click="handleSearchFunc"
        >查询</el-button
      >
    </template>
    <template slot="content">
      <!-- 表格 -->
      <customerTableDetail
        ref="newCusTable"
        :headers="tableHeaders"
        :checkHeaders="checkHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @edit="edit"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
        :headersConfig="true"
        :batchs="batchs"
        :selection="true"
        @batchClick="batchClick"
        :dynamic="true"
      >
      </customerTableDetail>
      <CustomerDetail ref="CustomerDetail"></CustomerDetail>
      <Distribute
        ref="Distribute"
        :noBtn="true"
        @clearBatchSelect="clearBatchSelect"
      />
    </template>
  </continer>
</template>

<script lang="ts">
/**
 * 客户表格
 */
import { Component, Vue, Ref, Watch } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import customerTableDetail from './customerTableDetail.vue'
import { commonAction, isHasFuncOrMenus, checkHideTel, deepClone } from '@/utils/common'
import CustomerDetail from '../drawer/customerDetail.vue'
import advancedSearch from '@/views/newCustomer/common/advanceSearch/advancedSearch.vue'
import customFilter from '@/components/customFilter/index.vue'
import inputType from '@/views/newCustomer/common/inputType.vue'
import Distribute from '@/views/newCustomer/components/buttons/distribute.vue'
import { CommonModule } from '@/store/modules/common/index'
@Component({
  name: 'NoticeSetting',
  components: {
    customerTableDetail,
    continer,
    CustomerDetail,
    advancedSearch,
    customFilter,
    inputType,
    Distribute
  }
})
export default class NoticeSetting extends Vue {
  [x: string]: any
  @Ref() private readonly CustomerDetail
  @Ref() private readonly Distribute
  private tableData: any = []

  private pagingData: any = { total: 0, limit: 10, page: 1 }

  private chooseFilterField: any = []

  private searchHeight: any = 0

  public formData: any = {}

  private filterId: any = ''

  private openShow: boolean = false

  private checkHeaders: any = []

  private tableHeaders: any = [
    { prop: 'name', label: '客户名称', show: true },
    { prop: 'source', label: '客户来源', show: true },
    { prop: 'labels', label: '客户标签', show: true },
    { prop: 'mobile', label: '手机号码', show: true },
    { prop: 'createTime', label: '创建时间', show: true },
    { label: '操作', prop: 'oprate', disenable: true, show: true }
  ]

  get getCustomerAllLabels () {
    let labelList = this.$store.state.common.publicCache.customerAllLabels || []
    labelList = labelList.filter(v => v.enabled)
    return labelList.map(v => ({ value: v.name, key: v._id }))
  }

  get getUserList () {
    return this.$store.state.common.publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get getRegionList () {
    return this.$store.state.common.publicCache.region.result || []
  }

  get getAllLabels () {
    return (CommonModule as any).publicCache.customerAllLabelsObj
  }

  get createMethods () {
    return [
      { key: 'INSERT', value: '录入' },
      { key: 'API', value: '标准接口' },
      { key: 'AUTOSAVE', value: '来电自动保存' },
      { key: 'IMPORT', value: '导入' },
      { key: 'WEBCHAT', value: '在线客服' },
      { key: 'WORKORDER', value: '工单' }
    ]
  }

  @Watch('$route', { immediate: true, deep: true })
  private routeChange (to: any, from: any) { // 服务记录详情跳转
    if (to.query.customerId) {
      this.$nextTick(() => {
        this.edit({ _id: to.query.customerId })
      })
    }
  }

  private getCusLables (id) {
    const labels = this.getAllLabels[id]
    if (labels && labels.name) {
      return labels
    }
    return {}
  }

  private handleLines () {
    this.openShow = !this.openShow
  }

  // private handleSearch (advanceQuery) {
  //   this.pagingData.page = 1
  //   console.log(advanceQuery, '高级搜索')
  //   this.customSearch.hide()
  //   this.getData()
  // }

  private fieldSelectList = { // 自定义选筛选下拉内容
    'status': [],
    'accessId': [],
    'finishKey': [],
    'seoSource': [],
    'platform': [],
    'toPeer': [],
    'userId': [],
    'sessionType': [],
    'satisfactionData.satisfactionName': [],
    'sessionTags': []
  }

  private conditionList: any = []
  private customList: any = []

  private getGender (type: any) {
    switch (type) {
      case 'F':
        return '女'
      case 'M':
        return '男'
      case 'N':
        return '保密'
    }
  }

  private getOperator (type: any) {
    switch (type) {
      case 'text':
        return 'eq'
      case 'multi-text':
        return 'eq'
      case 'dropdown':
        return 'in'
      case 'radio':
        return 'eq'
      case 'checkbox':
        return 'in'
      case 'cascade':
        return 'in'
      case 'date':
        return 'eq'
      case 'date-range':
        return 'between'
      case 'datetime':
        return 'eq'
      case 'datetime-range':
        return 'between'
      case 'number':
        return 'eq'
      case 'other':
        return 'in'
    }
  }

  private getFieldType (field: any) {
    const fieldObj: any = {} // 选中的搜索条件-以filed为key的对象
    this.chooseFilterField.map(item => {
      fieldObj[item.field] = item
    })
    if (fieldObj[field]) {
      const oper = (fieldObj[field].type && this.getOperator(fieldObj[field].type)) || ''
      return fieldObj[field].type
    }
  }

  private updatePropValue (val: any, field: any) {
    this.$set(this.formData, field, val)
  }

  private handleSearchData (search: any) {
    this.searchData = deepClone(this.formData)
    Object.keys(this.searchData).map(item => {
      const type = this.getFieldType(item)
      const operator = this.getOperator(type)
      if (type === 'cascade' && this.searchData[item] && this.searchData[item].length) { // 处理级联多级返回最后一级
        this.searchData[item].forEach((v, i) => {
          if (v && v.length) {
            if (typeof v === 'object') {
              v = v[v.length - 1]
            }
            this.$set(this.searchData[item], i, v)
          }
        })
      }
      if ((operator === 'eq' && this.searchData[item]) || (operator !== 'eq' && this.searchData[item] && this.searchData[item].length)) {
        search.push({
          field: item,
          value: operator === 'eq' ? [this.searchData[item]] : this.searchData[item],
          operator
        })
      }
    })
  }

  public async getData () {
    const search: any = [] // 搜索数据处理
    this.handleSearchData(search)
    const actionData: any = {
      limit: this.pagingData.limit,
      page: this.pagingData.page,
      filterId: this.filterId,
      search
    }
    const res: any = await commonAction({ url: '/server-crm/action/customer/list', method: 'POST', data: actionData })
    if (res.success) {
      this.tableData = res.data?.list || []
      this.pagingData.total = (res.data && res.data.count) || 0
    }
  }

  private handleSearchFunc () {
    this.pagingData.page = 1
    this.getData()
  }

  public getTableHeaders (filterId: any) { // 获取表格表头数据
    this.filterId = filterId
    const params = {
      url: '/server-crm/action/customer/config/header',
      method: 'GET',
      data: { filterId }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        res.data.headers.push({
          label: '操作', prop: 'oprate', disenable: true, show: true
        })
        this.$set(this, 'tableHeaders', res.data.headers || [])
        this.$set(this, 'checkHeaders', res.data.headers || [])
      }
    })
  }

  private checkHeadersChange (checkList: any, isInit: any) {
    if (!isInit) {
      this.$set(this, 'checkHeaders', checkList)
      const newArr = []
      checkList.forEach((item: any) => {
        if (item.prop !== 'oprate') {
          // @ts-ignore
          newArr.push(item)
        }
      })
      const params = { // 更新表头
        url: '/server-crm/action/customer/config/header',
        method: 'POST',
        data: {
          filterId: this.filterId,
          headers: newArr
        }
      }
      commonAction(params)
    }
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }

  private edit (item) {
    this.CustomerDetail.openDraw(item)
  }

  private batchs: any = [
    {
      name: '分配',
      action: 'distribute',
      _id: 'customer_assign'
    },
    {
      name: '删除',
      action: 'delete',
      _id: 'customer_delete'
    }
    // {
    //   name: '导出全部数据',
    //   action: 'export'
    // },
    // {
    //   name: '导出所选数据',
    //   action: 'exportSelect'
    // }
  ]

  public clearBatchSelect () {
    (this as any).$refs.newCusTable.cancelSelectFun()
    this.getData()
  }

  private batchClick (action: string, selectList: any) {
    let ids = []
    let condition = {}
    if (selectList === true) { // 全选
      ids = []
      const search: any = []
      this.handleSearchData(search)
      condition = { search, filterId: this.filterId }
    } else { // 部分选中
      ids = selectList
      condition = {}
    }
    switch (action) {
      case 'distribute':
        this.batchDistrubute(ids, condition)
        break
      case 'delete':
        this.batchDelete(ids, condition)
        break
    }
  }

  private batchDistrubute (ids, condition) {
    this.$confirm('确定要批量分配客户吗', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.$nextTick(() => {
        this.Distribute.openDialog(ids, condition, true)
      })
    })
  }

  private batchDelete (ids: any = [], condition = {}) {
    this.$confirm('确定要批量删除客户吗', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const params = {
        url: '/server-crm/action/customer/batchDelete',
        method: 'POST',
        data: {
          ids,
          condition
        }
      }
      commonAction(params).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.clearBatchSelect()
        }
      })
    })
  }

  get getCusAllFields () {
    const allFields = deepClone((CommonModule as any).publicCache.customerAllFields || [])
    const customFilterFields: any = [] // 自定义字段
    allFields.forEach(item => {
      if ((item.category === 'system' && !['attachment'].includes(item.type)) || (item.category === 'custom' && ['text', 'date', 'datetime', 'number', 'dropdown', 'cascade', 'checkbox', 'date-range', 'datetime-range'].includes(item.type))) {
        // 系统预置字段datetime => datetime-range
        if (item.category === 'system' && ['datetime'].includes(item.type)) {
          item.type = 'datetime-range'
        }
        customFilterFields.push(item)
      }
    })
    return customFilterFields
  }

  private saveFilter (data: any) {
    const params = {
      url: '/server-crm/action/customer/config/quicksearch/fields',
      method: 'POST',
      data
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success('保存成功')
        this.updateFilter(data.fields)
      }
    })
  }

  private updateFilter (chooseData: any) {
    // 人、标签等字段选项赋值
    chooseData.forEach(item => {
      if (item.field === 'labels') { // 客户标签
        item.choices = this.getCustomerAllLabels || []
      } else if (['lastCallUser', 'lastChatUser', 'updateUser', 'createUser', 'firstOwner', 'owner'].includes(item.field)) { // 跟人有关的字段
        item.choices = this.getUserList || []
      } else if (item.field === 'region') { // 省市区
        item.options = {}
        item.options.children = this.getRegionList || []
      } else if (item.field === 'createMethod') {
        item.choices = this.createMethods
      }
    })
    this.$set(this, 'chooseFilterField', chooseData)
    this.$nextTick(() => {
      this.searchHeight = document.getElementById('searchForm')?.offsetHeight
    })
  }

  public getFilterConf (filterId: any) {
    const params = {
      url: '/server-crm/action/customer/config/quicksearch',
      method: 'GET',
      data: { filterId }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        res.data.fields.map(item => {
          if (['mobile', 'qq', 'wechat', 'email'].includes(item.field)) {
            item.type = 'text'
          }
        })

        this.updateFilter(res.data.fields)
      }
    })
  }

  get getCustomerAllFields () {
    return this.$store.state.common.publicCache.customerAllFields || []
  }

  private mounted () {
    this.batchs = this.batchs.filter(item => isHasFuncOrMenus(item._id, this.$store.state.common.session.user, false)) // 批量操作权限过滤
  }
}
</script>
<style lang="stylus" scoped>
.cus-tags
  display inline-block
  padding 0 12px
  border-radius 12px
  margin 5px
>>> .el-form-item__label
  line-height 1
>>> .oprate
  margin-top 16px
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span, .disable-span
  color $c-danger
.open
  width 70px
  height 32px
  display flex
  align-items center
  justify-content center
  font-size 12px
  color #303854
  border 1px solid #E7E9ED
  border-radius 4px
  margin-right 10px
  cursor pointer
  i
    margin-right 5px
</style>
